# -*- coding:utf-8 -*-
__author__ = 'weikai'
import json
import traceback

from request_cic.login import *
from common.redisUtil import CRedis
from common.MqSend import send_mq
from request_cic.feebody2 import getFeebody, compare_date
from request_cic.cic_settings import headers
from my_dbUtil.dbInsert import soupDb
from request_cic import utils
from request_cic.translate import getPriumeInf
from request_cic.parse import parseFee
from common.log import Logger
global null, false, true
null = None
false = False
true = True
log=Logger()
#入参 session ，补全消息队列消息
def get_redis_body(requesteicc,dtjson):
    try:
        log.info(u"START  FROM REDIS GET CIC USERINFO")
        searchVin=dtjson['vinNo']
        #获取消息体
        r=CRedis()
        feedict=r.get_vin(searchVin,"4")
        if feedict==None:
            return 0
        #设置保险类型
        feedict=eval(feedict)
        log.info(u"CIC FROM REDIS GET USERINFO %s " % searchVin)
        #发送保费计算消息
        #解析保费
        seat=feedict.get("gNSeatNum","5")
        insuranceType=dtjson.get("insuranceType",{})
        insuranceTypeGroupId=insuranceType.get("insuranceTypeGroupId","")
        insuranceTypeGroup=insuranceType.get("insuranceTypeGroup","")
        insureCarId=dtjson['insureCarId']
        plateNo=dtjson.get("plateNumber","")
        client=dtjson['client']
        sessionId=dtjson['sessionId']
        isPhone=dtjson['isPhone']
        fee_url = 'http://carply.cic.cn/pcis/policy/universal/quickapp/actionservice.ai'
        feedict['insuranceType']=insuranceType
        log.info(u"拼装费用消息体")
        d = getFeebody(feedict)
        log.info(u"拼装费用消息体结束")
        feedata = 'ADAPTER_TYPE=JSON_TYPE&SERVICE_TYPE=ACTION_SERVIC&CODE_TYPE=CODE_TYPE&BEAN_HANDLE=baseAction&ACTION_HANDLE=perform&SERVICE_NAME=offerBizAction&SERVICE_MOTHOD=calcPremium&DW_DATA=' + d + '&HELPCONTROLMETHOD=common&SCENE=UNDEFINED&BIZ_SYNCH_CONTINUE=false&CUST_DATA=contiOfferMrk%253D1%2523%2523%2523multiOfferFlagMrk%253D1'
        log.info(u"发送费用计算请求")
        feeresp = requesteicc.post(url=fee_url, data=feedata, headers=headers)
        #print(feeresp.text)
        #feeresp = feeresp.json()
        feeresp = eval(feeresp.text)
        #print(feeresp.text)
        log.info(u"费用计算请求响应成功")


        if "终保日期" in feeresp['RESULT_MSG'] and "起保日期" in feeresp['RESULT_MSG'] :
            str1="\d{4}-\d{2}-\d{2}"
            datelist=re.findall(str1,feeresp['RESULT_MSG'],re.S)
            if len(datelist)==2:
                bigdate=compare_date(datelist[0],datelist[1])
                bigdate=compare_date(bigdate,utils.getlatedate(0))
                feedict['endDate']=bigdate
                d=getFeebody(feedict)
                feedata='ADAPTER_TYPE=JSON_TYPE&SERVICE_TYPE=ACTION_SERVIC&CODE_TYPE=CODE_TYPE&BEAN_HANDLE=baseAction&ACTION_HANDLE=perform&SERVICE_NAME=offerBizAction&SERVICE_MOTHOD=calcPremium&DW_DATA='+d+'&HELPCONTROLMETHOD=common&SCENE=UNDEFINED&BIZ_SYNCH_CONTINUE=false&CUST_DATA=contiOfferMrk%253D1%2523%2523%2523multiOfferFlagMrk%253D1'
                feeresp=requesteicc.post(url=fee_url,data=feedata,headers=headers)
                feeresp=feeresp.json()

        if len(feeresp['WEB_DATA']) > 0 and "起保日期" in feeresp['RESULT_MSG'] :
            log.info("中华联")
            feedt = parseFee(feeresp)
            lstrs = getPriumeInf(feedt)
            #print lstrs
            #data=[开始时间,结束时间，座位数，组合id (insureTypeGroupId )，车辆id，公司id]
            soupDb(lstrs, [feedict['endDate']+' 00:00:00', utils.getlatedate(365,feedict['endDate'])+" 23:59:59", seat,insuranceTypeGroupId,insureCarId,"4"])
            log.info(u"中华联 合入库成功:%s|%s" % (plateNo, searchVin))
            #将成功的消息体放入redis
            r.set_vin(searchVin,"4",json.dumps(feedict,ensure_ascii=False))
            send_mq(client,plateNo,"","1","4",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
            return 1
        if len(feeresp['WEB_DATA']) <= 0 or "重复投保"  in feeresp['RESULT_MSG']:
            log.error(u"中华联合 车架号：%s,错误信息%s:" % (searchVin, feeresp['RESULT_MSG'].replace("\n", "")))
            #返回错误信息
            msg=feeresp['RESULT_MSG'].replace("\n","")
            send_mq(client,plateNo,msg,"2","4",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
            return 0
    except Exception as e:
        log.error(traceback.format_exc())
        #send_mq(client,plateNo,"未知异常","2","4",sessionId,isPhone,insuranceTypeGroupId,insuranceTypeGroup)
        return 0